//
//  ViewController.m
//  Unity-iPhone
//
//  Created by ManuQiao on 16/7/7.
//
//

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic,strong)UIScrollView* sc;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 为了体现这个是自定义视图及控制器，随便在view上加点内容
//    [self.view setBackgroundColor:[UIColor greenColor]];
//    UILabel *label = [UILabel new];
//    [label setText:@"this is container view"];
//    [label setFrame:CGRectMake(100, 100, 0, 0)];
//    [label sizeToFit];
//    [self.view addSubview:label];
    
    UIView* scView = [UIView new];
    scView.frame = CGRectMake(0, 20, 100, 100);
    UIScrollView* sc =   UIScrollView.new;
//    sc.pagingEnabled = YES;
    self.sc = sc;
    sc.backgroundColor = UIColor.orangeColor;
    sc.frame  = CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 100);
    [self.view addSubview:sc];
    [self.view addSubview:scView];
    CGFloat width  = 50;
    NSInteger count = 20;
    for (NSInteger i =0; i<count; i++) {
        UIButton* button  = UIButton.new;
        [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        button.backgroundColor = self.randomColor;
        button.frame = CGRectMake(50*i, 20, width, 20);
        [sc addSubview:button];
    }
    sc.contentSize = CGSizeMake(width*count, 0);
    
}
- (void)click:(UIButton*)sender{
    CGFloat newOffsetX = sender.center.x - [UIScreen mainScreen].bounds.size.width*0.5;
    if (newOffsetX >= self.sc.contentSize.width - self.sc.frame.size.width) {//如果点击的button.center位于contentSize最大的那一页减去半页 那么  就让它一直停留在最后一页
        newOffsetX = self.sc.contentSize.width - self.sc.frame.size.width;
    }

    [UIView animateWithDuration:0.25 animations:^{
        if(newOffsetX>=0){
            [self.sc setContentOffset:CGPointMake(newOffsetX, 0)];
        }
        
    }];
    

}

-(UIColor *)randomColor
{
    CGFloat red = arc4random() % 256 / 255.0;
    CGFloat green = arc4random() % 256 / 255.0;
    CGFloat blue = arc4random() % 256 / 255.0;
    
    UIColor * color = [UIColor colorWithRed:red green:green blue:blue alpha:1];
    
    return color;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
